<template>
    <div>
        <!-- 文件上传 -->
        <v-row>
            <v-col cols="8">
                <v-file-input label="上传文件" v-model="uploadFiles" prepend-icon="mdi-upload" multiple show-size outlined
                    @change="handleFileUpload"></v-file-input>
            </v-col>
            <v-col cols="4">
                <v-btn color="primary" :disabled="!uploadFiles.length" @click="uploadAllFiles">
                    上传所有文件
                </v-btn>
            </v-col>
        </v-row>

        <!-- 文件上传结果提示 -->
        <v-snackbar v-model="snackbar.visible" :timeout="snackbar.timeout">
            {{ snackbar.message }}
            <template #actions>
                <v-btn color="white" text @click="snackbar.visible = false">关闭</v-btn>
            </template>
        </v-snackbar>
    </div>
</template>


<script setup>
import { ref } from 'vue';
import api from '@/utils/api';
const emit = defineEmits(['uploadSuccess']);
// 文件列表绑定
const uploadFiles = ref([]);

// Snackbar 配置
const snackbar = ref({
    visible: false,
    message: '',
    timeout: 3000,
});
// 上传所有文件
const uploadAllFiles = async () => {
    if (uploadFiles.value.length === 0) {
        showSnackbar('没有需要上传的文件！');
        return;
    }
    const results = await Promise.all(uploadFiles.value.map(api.uploadFile));

    const successCount = results.filter((result) => result.success).length;
    const failCount = results.length - successCount;

    // 上传完成后提示结果
    if (successCount > 0) {
        showSnackbar(`成功上传 ${successCount} 个文件！`);
        emit('uploadSuccess');
    }
    if (failCount > 0) {
        showSnackbar(`上传失败 ${failCount} 个文件，请重试！`);
    }

    // 清空文件选择
    uploadFiles.value = [];
};

// 显示 Snackbar
const showSnackbar = (message) => {
    snackbar.value.message = message;
    snackbar.value.visible = true;
};
</script>
